package com.hospes.rmes.asynctasks;

import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.hospes.rmes.adapters.NewsAdapter;
import com.hospes.rmes.core.databases.DataBaseManager;
import com.hospes.rmes.managers.NewsManager;
import com.hospes.rmes.models.News;
import com.hospes.rmes.utils.Utils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URL;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Andrew Khloponin
 * Date: 17.06.11
 */
public class NewsLoaderAsyncTask extends AsyncTask<Void, Void, Boolean> {
	private Context context;
	private ProgressBar dlgProgress;
	private ArrayList<News> newses = new ArrayList<News>();
	private NewsAdapter newsAdapter;

	public NewsLoaderAsyncTask(Context context, ProgressBar dlgProgress, NewsAdapter newsAdapter) {
		this.context = context;
		this.dlgProgress = dlgProgress;
		this.newsAdapter = newsAdapter;
	}

	@Override
	protected Boolean doInBackground(Void... cont) {
		try {
			URL url = new URL("http://rmes.com.ua/api/news");

			String jsontext = Utils.convertStreamToString(url.openStream());
			System.out.println(jsontext);
			JSONObject json = new JSONObject(jsontext);

			JSONArray jsonItems = json.getJSONArray("nodes");
			newses = NewsManager.getInstance().getNewsListFromJSON(jsonItems);
			DataBaseManager dataBaseManager = new DataBaseManager(context);
			dataBaseManager.openDB();
			dataBaseManager.insertData(newses);
			dataBaseManager.closeDB();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	protected void onPostExecute(Boolean response) {
		newsAdapter.setList(newses);
		newsAdapter.notifyDataSetChanged();
		dlgProgress.clearAnimation();
		dlgProgress.setVisibility(View.GONE);

		super.onPostExecute(response);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	public ArrayList<News> getNewses() {
		return newses;
	}
}
